<?php
declare(strict_types=1);
/**
 * 上传文件服务
 */
namespace Service\FileService;
use Service\BaseService;
use App\Model\PssModel\Sysconfig;
use Service\Code\Normal;
use PhpOffice\PhpSpreadsheet\IOFactory;
class UploadFileService extends BaseService
{
    /**
     * 上传文件服务
     * @param string $file
     */
    public function uploadFile(string $file)
    {
        $config = Sysconfig::instance()->getConfigByEventsValue('oss_config');
        if( empty($config['oss_way']) ) {
            return Normal::returnCode(Normal::FAIL,"上传三方配置文件不存在");
        }
        
        if( $config['oss_way'] == 'oss_qiniu' ) 
        {
            return QiniuFileService::instance()->uploadFile($config, $file);
        } 
        else if( $config['oss_way'] == 'oss_aliyun' )
        {
            return AliyunOssFileService::instance()->uploadFile($config, $file);
        }
        else
        {
            return Normal::returnCode(Normal::FAIL,"上传方式不存在!");
        }
    }
    
    /**
     * 根据前端传的后缀名获取资源信息
     * @param string $fileName
     */
    public function getRemoteUrlRowData($server,int $fd,string $fileName)
    {
        if( substr($fileName,0,2) == '/' ) {
            $fileName = substr($fileName,1);
        }
        
        $url            = $this->getOssURL();
        $remote_file    = $url."/".$fileName;
        $pathInfo       = pathinfo($remote_file);
        
        try 
        {
            $file_contents  = file_get_contents($remote_file);
            $send = Normal::returnWsStatus(Normal::WS_START, "进行中，读取远端文件完成", [
                'percent' => 0.01,
            ]);
            $server->push($fd,json_encode($send,JSON_UNESCAPED_UNICODE));
        }
        catch ( \Throwable $th)  
        {
            return Normal::returnCode(Normal::FAIL,"读取远端文件失败:[{$remote_file}],失败原因：{$th->getMessage()}，请重新上传文件之后，再试！");
        }
        
        $save_file_new_path = BASE_PATH.DIRECTORY_SEPARATOR."tmp/";
        if( !is_dir($save_file_new_path) ) 
        {
            mkdir($save_file_new_path);
            chmod($save_file_new_path,0777);
        }
        
        $extension = $pathInfo['extension'];
        $save_file_new_name = $save_file_new_path.date("YmdHis").'.'.$extension;
        file_put_contents($save_file_new_name,$file_contents);
        
        //读取excel文件
        try 
        {
            $result_read = $this->readExcel($save_file_new_name);
            if( $result_read['code'] != Normal::SUC ) {
                return $result_read;
            }
            
            $send = Normal::returnWsStatus(Normal::WS_START, "进行中，读取本地excel数据转换完成", [
                'percent' => 0.02,
            ]);
            $server->push($fd,json_encode($send,JSON_UNESCAPED_UNICODE));
            $data = $result_read['data'];
        } 
        catch ( \Throwable $th) 
        {
            return Normal::returnCode(Normal::FAIL,"读取excel文件失败:[{$fileName}],失败原因：{$th->getMessage()}，请检查excel文件是否带有以下不规范数据格式：【函数、过多的空行】");
        }
        
        if( empty($data) ) {
            return Normal::returnCode(Normal::FAIL,"当前上传表格数据缺少标题抬头！");
        }
        
        $header = current($data);
        unset($data[0]);
        if( empty($data) ) {
            return Normal::returnCode(Normal::FAIL,"当前上传表格没有真实未满足需要处理的数据!");
        }
        
        return Normal::returnCode(Normal::SUC,"获取数据成功",[
            'header'    => $header,
            'data'      => $data 
        ]);
    }
    
    /**
     * 导入excel文件数据
     * @param string $fileName
     */
    public function readExcel(string $fileName)
    {
        $spreadsheet = IOFactory::load($fileName);
        $worksheet = $spreadsheet->getActiveSheet();
        // 遍历工作表中的行
        $data = [];
        foreach ($worksheet->getRowIterator() as $row)
        {
            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(false);
            $rowData = [];
            foreach ($cellIterator as $cell) 
            {
                $rowData[] = $cell->getValue();
            }
            
            if ($rowData) 
            {
                $is_object = false;
                foreach ($rowData as $_r_data) 
                {
                    if( is_object($_r_data) ) 
                    {
                        $is_object = true;
                        break;
                    }
                }
                
                if( !$is_object ) {
                    $data[] = $rowData;
                } 
                else 
                {
                    return Normal::returnCode(Normal::FAIL,"读取excel数据格式错误，不能带有特殊符号数据!");
                }
            }
        }
        
        return Normal::returnCode(Normal::SUC,"获取成功",$data);
    }
    
    /**
     * 获取图片地址
     */
    public function getOssURL()
    {
        $config = Sysconfig::instance()->getConfigByEventsValue('oss_config');
        if( $config['oss_way'] == 'oss_qiniu' )
        {
            $config = Sysconfig::instance()->getConfigByEventsValue('oss_qiniu');
            return $config['upLoadURL'];
        }
        else
        {
            $config = Sysconfig::instance()->getConfigByEventsValue('oss_aliyun');
            return $config['url'];
        }
    }
}